package com.lagou.edu.factory;

import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class ProxyFactory {

    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public Object getCglibProxy(Object obj) {
        return Enhancer.create(obj.getClass(), (MethodInterceptor) (object, method, args, methodProxy) -> {
            this.transactionManager.beginTransaction();
            try {
                Object result = method.invoke(obj, args);
                this.transactionManager.commit();
                return result;
            } catch (Exception e) {
                this.transactionManager.rollback();
                throw e;
            }
        });

    }
}
